<?php

	function mySql2PhpTime($sqlDate){
		$arr = date_parse($sqlDate);
		return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);
	}

	function php2JsTime($date){
		return date("m/d/Y H:i", $date);
	}

	function mySql2JsTime($date){
		return php2JsTime(mySql2PhpTime($date));
	}

function getCalendarByRange($cID){
	$db = JFactory::getDBO();
	$db->setQuery("SELECT * FROM `#__jqcalendar` WHERE id=$cID");
	return $db->loadObject();
}

function getRegDate($uid){
	$db = JFactory::getDBO();
	$db->setQuery("SELECT registerDate FROM `#__users` WHERE id=$uid");
	return $db->loadResult();
}

$tpath	= JURI::base().'templates/'.JFactory::$application->getTemplate();
$cID=JRequest::getInt('id', 0, 'get');
$id		=JRequest::getInt("user_id",0);

if($cID){
	$event = getCalendarByRange($cID);
	$sarr = explode(" ", mySql2JsTime($event->StartTime));
	$earr = explode(" ", mySql2JsTime($event->EndTime));
	$rules=json_decode($event->RecurringRule);
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
	<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>Calendar Details</title>
	<link href="<?php echo $tpath?>/calendar/css/main.css" rel="stylesheet" type="text/css" />
	<link href="<?php echo $tpath?>/calendar/css/dp.css" rel="stylesheet" />
	<link href="<?php echo $tpath?>/calendar/css/dropdown.css" rel="stylesheet" />
	<link href="<?php echo $tpath?>/calendar/css/colorselect.css" rel="stylesheet" />

	<script src="<?php echo $tpath?>/calendar/src/jquery.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/common.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/jquery.form.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/jquery.validate.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/datepicker_lang_US.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/jquery.datepicker.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/jquery.dropdown.js" type="text/javascript"></script>
	<script src="<?php echo $tpath?>/calendar/src/Plugins/jquery.colorselect.js" type="text/javascript"></script>

	<script type="text/javascript">
		if (!DateAdd || typeof (DateDiff) != "function") {
			var DateAdd = function(interval, number, idate) {
				number = parseInt(number);
				var date;
				if (typeof (idate) == "string") {
					date = idate.split(/\D/);
					eval("var date = new Date(" + date.join(",") + ")");
				}
				if (typeof (idate) == "object") {
					date = new Date(idate.toString());
				}
				switch (interval) {
					case "y": date.setFullYear(date.getFullYear() + number); break;
					case "m": date.setMonth(date.getMonth() + number); break;
					case "d": date.setDate(date.getDate() + number); break;
					case "w": date.setDate(date.getDate() + 7 * number); break;
					case "h": date.setHours(date.getHours() + number); break;
					case "n": date.setMinutes(date.getMinutes() + number); break;
					case "s": date.setSeconds(date.getSeconds() + number); break;
					case "l": date.setMilliseconds(date.getMilliseconds() + number); break;
				}
				return date;
			}
		}
		function getHM(date)
		{
			 var hour =date.getHours();
			 var minute= date.getMinutes();
			 var ret= (hour>9?hour:"0"+hour)+":"+(minute>9?minute:"0"+minute) ;
			 return ret;
		}
		$(document).ready(function() {
			//debugger;
			var DATA_FEED_URL = "<?php echo JURI::base()?>index.php?option=com_datafeed&no_html=1";
			var arrT = [];
			var tt = "{0}:{1}";
			for (var i = 0; i < 24; i++) {
				arrT.push({ text: StrFormat(tt, [i >= 10 ? i : "0" + i, "00"]) }, { text: StrFormat(tt, [i >= 10 ? i : "0" + i, "30"]) });
			}
			$("#timezone").val(new Date().getTimezoneOffset()/60 * -1);
			$("#stparttime").dropdown({
				dropheight: 200,
				dropwidth:60,
				selectedchange: function() { },
<?php echo isset($event) ? "selecteditem:{text:'".$sarr[1]."'},":''; ?>
				items: arrT
			});
			$("#etparttime").dropdown({
				dropheight: 200,
				dropwidth:60,
				selectedchange: function() { },
<?php echo isset($event) ? "selecteditem:{text:'".$earr[1]."'},":'' ?>
				items: arrT
			});
			var check = $("#IsAllDayEvent").click(function(e) {
				if (this.checked) {
					$("#stparttime").val("00:00").hide();
					$("#etparttime").val("00:00").hide();
				}
				else {
					var d = new Date();
					var p = 60 - d.getMinutes();
					if (p > 30) p = p - 30;
					d = DateAdd("n", p, d);
					$("#stparttime").val(getHM(d)).show();
					$("#etparttime").val(getHM(DateAdd("h", 1, d))).show();
				}
			});
			if (check[0].checked) {
				$("#stparttime").val("00:00").hide();
				$("#etparttime").val("00:00").hide();
			}
			$("#Savebtn").click(function() { $("#fmEdit").submit(); });
			$("#Closebtn").click(function() { CloseModelWindow(); });
			$("#Deletebtn").click(function() {
				 if (confirm("Are you sure to remove this event")) {
					var param = [{ "name": "calendarId", value: <?php echo $event->Id?:0?>}];
					$.post(DATA_FEED_URL + "&method=remove",
						param,
						function(data){
							if (data.IsSuccess) {
									alert(data.Msg);
									CloseModelWindow(null,true);
								}
								else {
									alert("Error occurs.\r\n" + data.Msg);
								}
						}
					,"json");
				}
			});

		 $("#stpartdate").datepicker({ picker: "<button class='calpick'></button>"});
			var cv =$("#colorvalue").val() ;
			if(cv=="")
			{
				cv="-1";
			}
			$("#calendarcolor").colorselect({ title: "Color", index: cv, <?php if(!isset($event)){?>hiddenid: "colorvalue"<?php }?> });
			//to define parameters of ajaxform
			var options = {
				beforeSubmit: function() {
					return true;
				},
				dataType: "json",
				success: function(data) {
					alert(data.Msg);
					if (data.IsSuccess) {
						CloseModelWindow(null,true);
					}
				}
			};
			$.validator.addMethod("date", function(value, element) {
				var arrs = value.split(i18n.datepicker.dateformat.separator);
				var year = arrs[i18n.datepicker.dateformat.year_index];
				var month = arrs[i18n.datepicker.dateformat.month_index];
				var day = arrs[i18n.datepicker.dateformat.day_index];
				var standvalue = [year,month,day].join("-");
				return this.optional(element) || /^(?:(?:1[6-9]|[2-9]\d)?\d{2}[\/\-\.](?:0?[1,3-9]|1[0-2])[\/\-\.](?:29|30))(?: (?:0?\d|1\d|2[0-3])\:(?:0?\d|[1-5]\d)\:(?:0?\d|[1-5]\d)(?: \d{1,3})?)?$|^(?:(?:1[6-9]|[2-9]\d)?\d{2}[\/\-\.](?:0?[1,3,5,7,8]|1[02])[\/\-\.]31)(?: (?:0?\d|1\d|2[0-3])\:(?:0?\d|[1-5]\d)\:(?:0?\d|[1-5]\d)(?: \d{1,3})?)?$|^(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])[\/\-\.]0?2[\/\-\.]29)(?: (?:0?\d|1\d|2[0-3])\:(?:0?\d|[1-5]\d)\:(?:0?\d|[1-5]\d)(?: \d{1,3})?)?$|^(?:(?:16|[2468][048]|[3579][26])00[\/\-\.]0?2[\/\-\.]29)(?: (?:0?\d|1\d|2[0-3])\:(?:0?\d|[1-5]\d)\:(?:0?\d|[1-5]\d)(?: \d{1,3})?)?$|^(?:(?:1[6-9]|[2-9]\d)?\d{2}[\/\-\.](?:0?[1-9]|1[0-2])[\/\-\.](?:0?[1-9]|1\d|2[0-8]))(?: (?:0?\d|1\d|2[0-3])\:(?:0?\d|[1-5]\d)\:(?:0?\d|[1-5]\d)(?:\d{1,3})?)?$/.test(standvalue);
			}, "Invalid date format");
			$.validator.addMethod("time", function(value, element) {
				return this.optional(element) || /^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/.test(value);
			}, "Invalid time format");
			$.validator.addMethod("safe", function(value, element) {
				return this.optional(element) || /^[^$\<\>]+$/.test(value);
			}, "$<> not allowed");
			$("#fmEdit").validate({
				submitHandler: function(form) { $("#fmEdit").ajaxSubmit(options); },
				errorElement: "div",
				errorClass: "cusErrorPanel",
				errorPlacement: function(error, element) {
					showerror(error, element);
				}
			});
			function showerror(error, target) {
				var pos = target.position();
				var height = target.height();
				var newpos = { left: pos.left, top: pos.top + height + 2 }
				var form = $("#fmEdit");
				error.appendTo(form).css(newpos);
			}
		});
	</script>
	<style type="text/css">
	.calpick	 {
		width:16px;
		height:16px;
		border:none;
		cursor:pointer;
		background:url("templates/fitplan/calendar/css/images/icons/cal.gif") no-repeat center 2px;
		margin-left:-22px;
	}
	.inline{display:inline !important}
	.mr110{margin-right: 110px}
	.mr50{margin-right: 50px}
	.w200{width: 200px}
	.fr{float: right}
	.clr{clear:both}
	.xsep{display: inline;padding:5px 10px}
	</style>
</head>
<body>
	<div style="height: 100%">
	<div class="toolBotton">
		<a id="Savebtn" class="imgbtn" href="javascript:void(0);">
		<span class="Save"title="Save the calendar">Save(<u>S</u>)
		</span>
		</a>
		<?php if(isset($event)){ ?>
		<a id="Deletebtn" class="imgbtn" href="javascript:void(0);">
		<span class="Delete" title="Cancel the calendar">Delete(<u>D</u>)
		</span>
		</a>
		<?php } ?>
		<a id="Closebtn" class="imgbtn" href="javascript:void(0);">
		<span class="Close" title="Close the window" >Close
		</span></a>
		</a>
	</div>
	<div style="clear: both">
	</div>
	<div class="infocontainer" style="height: 88%">
		<form action="<?php echo JURI::base()?>index.php?option=com_datafeed&no_html=1&method=adddetails<?php echo isset($event)?"&id=".$event->Id:"&sid=".$id; ?>" class="fform" id="fmEdit" method="post">
		<label>
					<span>*Subject:</span>
			<div id="calendarcolor">
			</div>
			<input MaxLength="200" class="required safe" id="Subject" name="Subject" style="width:85%;" value="<?php echo isset($event)?$event->Subject:"" ?>" />
			<input id="colorvalue" name="colorvalue" type="hidden" value="<?php echo isset($event)?$event->Color:"" ?>" />
		</label>
		<label>
					<span>*Time:</span>
			<div>
			<input MaxLength="10" class="required date" id="stpartdate" name="stpartdate" style="padding-left:2px;width:90px;" value="<?php echo isset($event)?$sarr[0]:""; ?>" />
			<input MaxLength="5" class="required time" id="stparttime" name="stparttime" style="width:40px;" value="<?php echo isset($event)?$sarr[1]:""; ?>" />
			<input type="hidden" MaxLength="10" class="required date" id="etpartdate" name="etpartdate" style="padding-left:2px;width:90px;" value="<?php echo isset($event)?$earr[0]:""; ?>" />
			<input type="hidden" MaxLength="50" class="required time" id="etparttime" name="etparttime" style="width:40px;" value="<?php echo isset($event)?$earr[1]:""; ?>" />
				<input id="IsAllDayEvent" name="IsAllDayEvent" type="hidden" value="0" <?php //if(isset($event)&&$event->IsAllDayEvent!=0) {echo "checked";}All Day Event?>/>	
			<!--label class="checkp">
			</label-->
			</div>
		</label>
		<label style="display: none">
					<span>Location:</span>
			<input type="hidden" MaxLength="200" id="Location" name="Location" style="width:95%;" value="<?php echo isset($event)?$event->Location:""; ?>" />
		</label>
		<label style="display: none">>
					<span>Remark:</span>
<input type="hidden" name="Description" value=""/>
<!--textarea cols="20" id="Description" name="Description" rows="2" style="width:95%; height:70px">
<?php echo isset($event)?$event->Description:""; ?>
</textarea-->
		</label>
<!--custom options-->
		<div>
					<span style="font-weight: 700">GENTAGES:</span>
			<label class="w200 clr">Kun denne gang<input id="repeat1" name="repeat" class="fr" type="radio" value=0<?php if(!$rules) echo ' checked=""'?> /></label>
			<label class="w200 clr">Alle hverdage<input id="repeat2" name="repeat" class="fr" type="radio" value=1<?php if($rules) echo ' checked=""'?> /></label>
			<br />

			<div id="dayset"<?php if(!$rules) echo 'style="display:none"'?>>
			<label class="w200 mr50 clr"><b>Gentag på:</b></label>
<?php
$daynames=array("M",
			"T",
			"O",
			"T",
			"F",
			"L",
			"S"
			);
$i=0;
foreach($daynames as $v){
	
?>
			<input class="dchkbx" type="checkbox" name="wd[]" value=<?php echo ++$i;if($rules AND in_array($i,$rules->weekdays)) echo ' checked=""'?> /><?php echo $v?>
<?php }?>
			</div>

			<div id="weekset" style="<?php if (!$rules) echo 'display:none;'?>overflow-x:scroll;">
			<label class="w200 mr50 clr"><b>I uge:</b></label>
			<table><tbody><th>1</th><?php $i=2;$j=53;
			while($i<$j){
				echo "<th>",$i++,"</th>";
			}
			?>
			<tr>
<?php
$i=0;
while(++$i<$j){?>
			<td><input type="checkbox" class="wselect" name="w[]"  value=<?php echo $i;if($rules AND in_array($i,$rules->weeks)) echo ' checked=""'?> /></td>
<?php }?>
			</tr>
			</tbody></table>
			</div>
		</div>
		<input id="timezone" name="timezone" type="hidden" value="" />
		</form>
	</div>
	</div>
<script type="text/javascript">
<?php if(!$event){//New notification, addDetails, inside iframe?>
	var a=window.parent.document.getElementById("bbit-cal-start").value.split(" ");
	var b=a[0].split("-");
	b=[b[1],b[2],b[0]];
	$("#stpartdate").val(b.join("/"));
	$("#stparttime").val(a[1]);
	a=window.parent.document.getElementById("bbit-cal-end").value.split(" ");
	b=a[0].split("-");
	b=[b[1],b[2],b[0]];
	$("#etpartdate").val(b.join("/"));
	$("#etparttime").val(a[1]);
<?php }?>
$('#repeat1').click(function(e){
	if(this.checked){$('#dayset').hide();$('#weekset').hide()}
});
$('#repeat2').click(function(e){
	if(this.checked){$('#dayset').show();$('#weekset').show()}
});
if($("#fmEdit").attr("action").indexOf("&id=")){

	tmp=window.parent.document.getElementById("bbit-cal-start").value;
	tmp=tmp.replace(/-/g,"/");
	var a=new Date(tmp);
	aa=a.getDay();
	aa=(aa) ? aa-1:6;//0 is Sunday, idx=6 in array
	a=a-aa*86400000;//force selected day to Monday
	aa=$('input[name="wd[]"]')[aa];
	aa.setAttribute("checked",true);
	
	var b=new Date("<?php echo mySql2JsTime(getRegDate($id))?>");
	bb=b.getDay();
	bb=(bb) ? bb-1:6;
	b=b-bb*86400000;//force register day to Monday

	var c=-1;
	a=Math.round((a-b)/604800000);
	if(a>=0){
		c=a-1;
	}

	if((c=$('input[name="w[]"]')[c]))
		c.setAttribute("checked",true);
}
</script>
</body>
</html>